from  autoui.core.dosqlite import Dosqlite
import json
import time
import zlib
from mitmproxy import  http
class test:
    def __init__(self):
        self.d=Dosqlite()
    def request(self,flow):
        # if flow.request.host=='paytest.ciicsh.com':
        # ctx.log.info(dir(flow.request))
        # if flow.request.host=='paytest.ciicsh.com':
        

        req={}
        req['time']=time.time()
        # print('-'*20)
        # print(flow.id)
        req['method']=flow.request.method
        req['url']=flow.request.pretty_url
        req['data']= flow.request.text
        
        # print(flow.request.text)
        # print(flow.request.multipart_form)
        # print(flow.request.pretty_host)
        # print(flow.request.pretty_url)
        # print(flow.request.urlencoded_form)
        # for i in flow.request.headers
        # print(dir(flow.request.headers))
        dd={}
        for k,v in flow.request.headers.items():
            dd[k]=v
        if 'Content-Type' in dd:
            req['con']=dd['Content-Type']
        else:
            req['con']=''
        req['header']=json.dumps(dd,ensure_ascii=False)
        
        req['fid']=flow.id
        if 'myseleniumelement' in flow.request.pretty_url:

            self.d.run("INSERT INTO element( fid, method, url, header, data, 'context-type', time) VALUES ( '{fid}', '{method}', '{url}', '{header}', '{data}', '{con}', {time})".format(**req))
            flow.response = http.HTTPResponse.make(204)
            
        else:
            

            self.d.run("INSERT INTO request( fid, method, url, header, data, 'context-type', time) VALUES ( '{fid}', '{method}', '{url}', '{header}', '{data}', '{con}', {time})".format(**req))
            # print(req)
            # print(flow.request.pretty_url)

            # print('-'*20)
    def http_connect(self, flow):
        hei=['update.googleapis.com','www.gstatic.com','r2---sn-ni57rn7k.gvt1.com']
        if flow.request.host in hei:
            flow.response = http.HTTPResponse.make(404)
        
            
    def response(self,flow):
        no_body_type=['.woff']
        res={}
        res['time']=time.time()
        res['fid']=flow.id
        res['code']=flow.response.status_code
        res['msg']=flow.response.reason
        dd={}
        for k,v in flow.response.headers.items():
            dd[k]=v
        if 'Content-Type' in dd:
            res['con']=dd['Content-Type']
        else:
            res['con']=''
        res['header']=json.dumps(dd,ensure_ascii=False)
        res['text']=flow.response.text.replace("'",r"zheliyuanlaiyougedanyinhao").replace('\r','').replace('\n',r'zheliyuanlaiyougehuanhang').replace("\"",r"zheliyuanlaiyougeshuangyinhao").replace("\t",r"zheliyuanlaiyouget")
        res['url']=flow.request.pretty_url
        res['save']='text'
        # if res['url']=='https://paytest.ciicsh.com/login?redirect=%2FsalaryMgr%2FsalaryConfig':
        #     raise Exception(str(type(flow.response.content))+str(flow.response.content))
        # raise  Exception(str(type(res['text']))+res['url'])
        if res['con'].startswith('image'):
            import base64

            res['text']=base64.b64encode(flow.response.content).decode('utf8')
            res['save']='base64'

            # if '"' in res['text'] :
            #     raise  Exception('has1')
            # if '\'' in res['text'] :
            #     raise  Exception('has2')

            # raise  Exception(str(type(res['text'])))
        for i in no_body_type:
            
            if res['url'].endswith(i):
                res['save']='no'
                res['text']=''
        try:
            
            self.d.run(" INSERT INTO response( url,fid, code, msg, header, text, 'content-type','save-type', time) VALUES ( '{url}','{fid}', '{code}', '{msg}', '{header}', '{text}', '{con}', '{save}',{time})".format(**res))
        except Exception as e:
            with open('text.txt','a',encoding='utf8') as f:
                f.write(" INSERT INTO response( url,fid, code, msg, header, text, 'content-type','save-type', time) VALUES ( '{url}','{fid}', '{code}', '{msg}', '{header}', '{text}', '{con}', '{save}',{time})".format(**res)+'\n')
            raise  Exception(res['url']+str(e))
        
        


        # raise  Exception(str(res))
        # print(flow.id)
        #print(dir(flow))
        
            
addons=[test()]